#import "MyView.h"
#import <appkit/Control.h>
#import <appkit/Form.h>
#import <appkit/Application.h>
#import <dpsclient/wraps.h>
#import <strings.h>
#include <stdio.h>

@implementation MyView

static char logString[10000];

/* add a string to the log and have text updated */
static void addStringLog(target, string)
char *string;
id target;
{
	strcat(logString, string);
	[target setStringValue:logString];
}

/* add an event to the log text */
static void addEventLog(target, string, x, y, type)
char *string;
id target;
float x,y;
int type;
{
static char tmpString[100];
	strcat(logString, string);
	if (type == 1) strcat(logString, " DOWN ");
       else if (type == 2) strcat(logString, " UP ");
          else if (type == 6) strcat(logString, " DRAG ");
             else {
			   sprintf(tmpString, " type=%d ", type);
			   strcat(logString, tmpString);
			 }
	sprintf(tmpString, "at x=%3.0f  y=%3.0f\n", x, y);
	strcat(logString, tmpString);
	[target setStringValue:logString];
}


- setXForm:anObject
{
    xForm = anObject;
    return self;
}

- setYForm:anObject
{
    yForm = anObject;
    return self;
}

- setLogText:anObject
{
    logText = anObject;
    return self;
}

- clearLog:sender
{
	logString[0] = '\0';
	[logText setStringValue:logString];
	return self;
}

- drawSelf:(NXRect *)list:(int)count
{
    NXEraseRect(&bounds);
	return self;
}

// from chapter 7 page 61
- mouseDown:(NXEvent *)thisEvent
{
	register int	 inside; 
	int				 shouldLoop = YES; 
	int				 oldMask; 
	NXEvent			*nextEvent;
	NXPoint	mLoc, oldLoc, myPoint;
	BOOL flipped = NO;
	
	oldLoc = thisEvent->location;
    addEventLog(logText, "Enter mouseDown", oldLoc.x, oldLoc.y, thisEvent->type);
	// [self doMyOwnHighlight];
	oldMask = [window addToEventMask:NX_LMOUSEDRAGGEDMASK];

	while (shouldLoop) { 
		nextEvent = [NXApp getNextEvent:(NX_LMOUSEUPMASK | NX_LMOUSEDRAGGEDMASK)];
		mLoc = nextEvent->location;
		addEventLog(logText, "NextEvent Window Coords:", mLoc.x, mLoc.y, nextEvent->type);
		[self convertPoint:&mLoc fromView:nil];
		// mLoc = nextEvent->location;
		addEventLog(logText, "View Coords:", mLoc.x, mLoc.y, nextEvent->type);
		inside = NXMouseInRect(&mLoc, &bounds, flipped);
		[xForm setFloatValue:mLoc.x at:0];
	    [yForm setFloatValue:mLoc.y at:0];
		switch (nextEvent->type) { 
		case NX_LMOUSEUP:  
			shouldLoop = NO; 
			if ( inside ) {
				addStringLog(logText, "Mouse Up Inside View\n");
				// [self doMyOwnHighlight]; 
				// [self doMyOwnThing]; 
			} 
			// [self doMyOwnUnhighlight]; 
			break; 
		case NX_LMOUSEDRAGGED:  
			if ( inside ) 
				addStringLog(logText, "Mouse Drag Inside View\n");
				// [self doMyOwnHighlight]; 
			else 
				addStringLog(logText, "Mouse Drag Outside View\n");
				// [self doMyOwnUnhighlight]; 
			break; 
		default:
			addEventLog(logText, "In Default", mLoc.x, mLoc.y, nextEvent->type); 
			break; 
		}

	} 
	[window setEventMask:oldMask]; 
	return(self); 
}


@end
